package modules

import (
	_ "github.com/go-sql-driver/mysql"
	"github.com/topfreegames/pitaya/config"
	"github.com/xormplus/xorm"
)


type DatabaseStorage struct {
	Base
	config  *config.Config
	Enginer *xorm.Engine
}

func NewDatabaseStorage(conf *config.Config) (*DatabaseStorage,error) {
	d := &DatabaseStorage{
		config: conf,
	}
	err := d.configure()
	if err != nil {
		return nil,err
	}
	return d,nil;
}

func (d *DatabaseStorage) configure() error  {
	var err error
	d.Enginer,err = xorm.NewEngine("mysql",d.config.GetString("pitaya.modules.databasestorage.engine.datasourcename"))
	if err != nil {
		return err
	}
	//d.Enginer.SetLogger(logger.Log)
	d.Enginer.ShowSQL(true)
	d.Enginer.SetMaxIdleConns(d.config.GetInt("pitaya.modules.databasestorage.Enginer.maxidleconns"))
	d.Enginer.SetMaxOpenConns(d.config.GetInt("pitaya.modules.databasestorage.Enginer.maxopenconns"))
	d.Enginer.SetConnMaxLifetime(d.config.GetDuration("pitaya.modules.databasestorage.Enginer.connmaxlifetime"))
	return err
}

func (d *DatabaseStorage) Init() error {
	var err error
	err = d.Enginer.Ping()
	if err != nil {
		return err
	}

	return err
}

func (d *DatabaseStorage) Shutdown() error  {
	return d.Enginer.Close()
}